import socket
import os

def get_file_info(path):
    files_and_folders = []
    for f in os.listdir(path):
        full_path = os.path.join(path, f)
        if os.path.isdir(full_path):
            files_and_folders.append((f"{f}/", 0))  # 文件夹大小为0
        elif os.path.isfile(full_path):
            size_mb = os.path.getsize(full_path) / (1024 * 1024)  # 转换为MB
            files_and_folders.append((f, size_mb))  # 文件大小
    return files_and_folders

def send_file(client_socket, file_path):
    print(client_socket,file_path)
    #<socket.socket fd=628, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 2121), raddr=('127.0.0.1', 38885)> F:/Android\萝莉2.mp4

    #return None
    file_size_mb = os.path.getsize(file_path) / (1024 * 1024)  # 转换为MB
    with open(file_path, 'rb') as file:
        while True:
            data = file.read(1024)
            if not data:
                break
            client_socket.sendall(data)
    client_socket.sendall(f"File {os.path.basename(file_path)} sent. Size: {file_size_mb:.2f} MB".encode('gbk'))

def handle_client(client_socket, base_path):
    while True:
        files_and_folders_info = get_file_info(base_path)
        client_socket.sendall(str(files_and_folders_info).encode('gbk'))  # 使用GBK编码发送文件名和大小
        response = client_socket.recv(1024).decode('gbk')  # 使用GBK编码接收客户端消息
        if response == "ls":
            continue
        elif response == "../":
            base_path = os.path.dirname(base_path)
            continue
        try:
            index = int(response)
            selected = [name for name, size in files_and_folders_info][index]
            selected_path = os.path.join(base_path, selected.rstrip('/'))
            if os.path.isdir(selected_path):
                base_path = selected_path
            else:
                send_file(client_socket, selected_path)
                break
        except (IndexError, ValueError):
            client_socket.sendall("Invalid input".encode('gbk'))  # 使用GBK编码发送错误消息
            break

def start_server(host, port, base_path):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen()
    print(f"Server listening on {host}:{port}")

    while True:
        client_socket, addr = server_socket.accept()
        print(f"Connected by {addr}")
        handle_client(client_socket, base_path)
        client_socket.close()

if __name__ == "__main__":
    start_server('localhost', 2121, 'F:/百度下载')